import {Injectable} from '@angular/core';
import {HttpClient, HttpErrorResponse} from "@angular/common/http";
import {catchError, Observable, of, tap} from "rxjs";
import {map} from "rxjs/operators";
import {DomSanitizer} from '@angular/platform-browser';
//import {environment} from "../../environments/environment";
import {environment} from 'src/environments/environment';

@Injectable()
export class ApiService {

  constructor(private http: HttpClient, private domSanitizer: DomSanitizer) { }

  getProtectedApiResponse(): Observable<string> {
    console.log("查看是否拦截=====test/user ")
    return this.http.get<any>(environment.baseUrl+ '/messages',  {withCredentials: true, headers: {'Content-Type': 'application/json' }})
      .pipe(

        tap(response => console.log('访问API 成功===== '+response)),

        map(response => this.extractStringValue(response)),
        map(value => `api success form ${value}`),

        catchError(this.handleError)
      );
      ;

  }

  getApiMessage(): any  {
     this.http.get<any>(environment.baseUrl + '/messages/admin',  {withCredentials: true, headers: {'Content-Type': 'application/json' }}).subscribe(
      response=>{console.log('访问无权限的API 成功===== '+response)

      },
      error=>{console.log('访问无权限的API 失败===== '+error)

      }
    )

  }




  private extractStringValue(response: MessageResponse[]): string | null {
    //const stringMessage = response.find((i: MessageResponse) => i.type === 'string');
    const stringMessage = response.toString()
    return stringMessage ? stringMessage : null;
  }

  private handleError(error: HttpErrorResponse): Observable<string> {
    // 这里可以连接到错误监控系统，或者使用统一的错误处理服务
    console.error('API错误', error); // 使用更合适的日志级别
    return of(`api error: ${error.status} ${error.statusText} ${error.message}`);
  }

  //===============================================
  //===============================================
  // loadPage(url: string): Observable<SafeHtml> {
  //   return this.http.get(url, { responseType: 'text', headers: {'Content-Type': 'application/json' }} ).pipe(
  //     tap(html => console.log('loadPage访问页面成功===== '+html)),
  //     map(html => this.sanitizeHtml(html))
  //   );
  // }
  //
  // sanitizeHtml(html: string): SafeHtml {
  //   return this.domSanitizer.bypassSecurityTrustHtml(html);
  // }

  loadPage(url: string): Observable<string> {
    return this.http.get(url, { responseType: 'json' })
      .pipe(map(b=>b.toString()))

      ;
  }

}

// 假设定义了一个接口来描述HTTP响应的结构
export  interface MessageResponse {
  type: string;
  value: string;
}
